package com.xxl.job.admin.core.util;

import com.xxl.job.admin.core.model.XxlJobSyncLock;
import com.xxl.job.admin.dao.XxlJobSyncLockDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LockUtil {

    private static Logger logger = LoggerFactory.getLogger(LockUtil.class);

    public static boolean lock(int jobId, XxlJobSyncLockDao xxlJobSyncLockDao){
        XxlJobSyncLock xxlJobSyncLock = new XxlJobSyncLock();
        xxlJobSyncLock.setLockId(jobId);
        int count = xxlJobSyncLockDao.save(xxlJobSyncLock);
        if (count == 0) { // 说明已经有数据存在
            return false;
        }
        logger.info("线程[{}]获取到锁[{}]", Thread.currentThread().getName(),jobId);
        return true;
    }

    public static void unlock(int jobId, XxlJobSyncLockDao xxlJobSyncLockDao){
        xxlJobSyncLockDao.delete(jobId);
        logger.info("线程[{}]释放锁[{}]", Thread.currentThread().getName(), jobId);
    }

}
